package miao

import (
	"errors"
	"fmt"
	"miao-va-host/global"
	"miao-va-host/lib/cmdutil"
	"miao-va-host/model"
	"os"
	"path/filepath"
	"time"
)

var Plugin = new(plugin)

type plugin struct {
}

func (p *plugin) RunPipe(conf model.PluginPipeInstruct) (err error) {
	option := cmdutil.CommandOption{
		User: conf.User,
		Env:  conf.Env,
	}
	cr, err := os.Executable()
	if err != nil {
		return
	}
	argus := make([]string, 0)
	argus = append(argus, filepath.Join(filepath.Dir(cr), global.PluginFolder, conf.Cmd))
	argus = append(argus, conf.Args...)
	cmdutil.RunCommandArgsForPipe(argus, option, conf.OutChan, conf.CloseChan, conf.Cancel)
	return
}

func (p *plugin) Run(conf model.PluginInstruct) (stdout string, err error) {
	option := cmdutil.CommandOption{
		TimeoutDuration: time.Duration(conf.TimeoutDuration) * time.Second,
		User:            conf.User,
		Env:             conf.Env,
	}
	cr, err := os.Executable()
	if err != nil {
		return
	}
	argus := make([]string, 0)
	argus = append(argus, filepath.Join(filepath.Dir(cr), global.PluginFolder, conf.Cmd))
	argus = append(argus, conf.Args...)
	stdout, stderr, exitCode, err := cmdutil.RunCommandArgs(argus, option)
	if err != nil {
		err = errors.New(fmt.Sprintf("插件调用时发生错误:[err: %v ],[exitCode:%d],[stdout:%s],[stderr:%s]", err, exitCode, stdout, stderr))
		return
	}
	return stdout, nil
}
